import { ref, computed, onBeforeMount, nextTick, onUnmounted } from 'vue';
import { loginApi, getUserInfoApi, getUserExtInfoApi, setUserExtInfoApi, registApi, sendRegistVerifyCodeApi, sendModifyPwdVerifyCodeApi, modifyUserPwdApi } from '@/plugins/http/api/user';
import { StorageSerializers, useStorage, useLocalStorage } from '@vueuse/core';
import { isNotEmpty, getDeviceType, saveUser2Db } from '@/plugins/util.js'

import { useToast } from '@/composition/useToast.js'
import { useConfirm } from '@/composition/useConfirm'
import { isEmpty } from '../plugins/util';

const { successToast, errorToast } = useToast()
const { showConfirm } = useConfirm()


const generateUUID = () => {
    let d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

const getBgImgUrlPcDefault = () => {
    return [
        {
            uuid: generateUUID(),
            checked: true,
            name: '自用-动漫',
            // url: 'http://192.168.168.1:8888/img/getRandomImg/动漫',
            // url: 'https://api.ystel.cn/img/getRandomImg/动漫'
            url: '/api/img/getRandomImg/动漫'
            // url: 'http://eq59.ystel.cn:7080/api/img/getRandomImg/动漫'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '自用-最新',
            // url: 'http://192.168.168.1:8888/img/getRandomImg/最新',
            // url: 'https://api.ystel.cn/img/getRandomImg/最新'
            url: '/api/img/getRandomImg/最新'
            // url: 'http://eq59.ystel.cn:7080/api/img/getRandomImg/最新'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '随机',
            url: 'https://picsum.photos/1920/1080'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '随机Bing壁纸',
            url: 'https://api.yimian.xyz/img?type=wallpaper'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '二次元自适应',
            url: 'https://t.mwm.moe/ycy'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '萌版自适应',
            url: 'https://t.mwm.moe/moez/'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '动漫AI自适应',
            url: 'https://t.mwm.moe/ai'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '二次元风景',
            url: 'https://t.mwm.moe/fj'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '随机二次元图片',
            url: 'https://api.yimian.xyz/img?type=moe'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '随机二次元',
            url: 'https://api.asxe.vip/random.php'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '超级小兔的随机图',
            url: 'https://imgapi.xl0408.top/index.php'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '樱花随机二次元图片',
            url: 'https://www.dmoe.cc/random.php'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '素颜-原神',
            url: 'https://api.suyanw.cn/api/ys'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '素颜-随机二次元',
            url: 'https://api.suyanw.cn/api/comic/api.php'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '素颜-随机动漫',
            url: 'https://api.suyanw.cn/api/360bizhi.php?type=image'
        },
        // {
        //     uuid: generateUUID(),
        //     checked: false,
        //     name: '随机二次元',
        //     url: 'https://www.loliapi.com/acg/'
        // },
    ];
}

const getBgImgUrlMobileDefault = () => {
    return [
        {
            uuid: generateUUID(),
            checked: true,
            name: '自用-动漫',
            // url: 'http://192.168.168.1:8888/img/getRandomImg/动漫',
            // url: 'https://api.ystel.cn/img/getRandomImg/动漫',
            url: '/api/img/getRandomImg/动漫',
            // url: 'http://eq59.ystel.cn:7080/api/img/getRandomImg/动漫',
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '自用-最新',
            // url: 'http://192.168.168.1:8888/img/getRandomImg/最新',
            // url: 'https://api.ystel.cn/img/getRandomImg/最新',
            url: '/api/img/getRandomImg/最新',
            // url: 'http://eq59.ystel.cn:7080/api/img/getRandomImg/最新',
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '随机',
            url: 'https://picsum.photos/1080/1920'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '二次元自适应',
            url: 'https://t.mwm.moe/ycy'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '萌版自适应',
            url: 'https://t.mwm.moe/moez/'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: 'AI自适应',
            url: 'https://t.mwm.moe/ai'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '超级小兔的随机图',
            url: 'https://imgapi.xl0408.top/index.php'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '素颜-原神',
            url: 'https://api.suyanw.cn/api/ys'
        },
        {
            uuid: generateUUID(),
            checked: false,
            name: '素颜-随机二次元',
            url: 'https://api.suyanw.cn/api/comic/api.php'
        },
        // {
        //     uuid: generateUUID(),
        //     checked: false,
        //     name: '随机二次元',
        //     url: 'https://www.loliapi.com/acg/'
        // },
    ]
}

const getSearchEnginesDefault = () => {
    return [
        {
            uuid: generateUUID(),
            isDefault: true,
            name: '必应',
            url: 'https://cn.bing.com/search?q=%s'
        },
        {
            uuid: generateUUID(),
            isDefault: false,
            name: '百度',
            url: 'https://www.baidu.com/s?word=%s'
        },
        {
            uuid: generateUUID(),
            isDefault: false,
            name: '谷歌',
            url: 'https://www.google.com/search?q=%s'
        }
    ]
}

const getGuidesDefault = () => {
    return [
        {
            name: 'Portainer',
            icon: 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=Portainer',
            url: 'https://portainer.ystel.cn/',
            // url: 'http://192.168.168.1:9000/',
            desc: ''
        },
        {
            name: 'Jenkins',
            icon: 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=Jenkins',
            url: 'https://jenkins.ystel.cn/',
            // url: 'http://192.168.168.1:8090/',
            desc: ''
        },
        {
            name: 'Alist',
            icon: 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=Alist',
            url: 'https://alist.ystel.cn/',
            // url: 'http://192.168.168.1:5244/',
            desc: ''
        },
        {
            name: '小雅',
            icon: 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=小雅',
            url: 'https://xiaoya.ystel.cn/',
            // url: 'http://192.168.168.1:6789/',
            desc: ''
        },
        {
            name: 'DDNS-GO',
            icon: 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=DDNS-GO',
            url: 'https://ddns-go.ystel.cn/',
            // url: 'http://192.168.168.1:9876/',
            desc: ''
        },
        {
            name: 'NPM',
            icon: 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=NPM',
            url: 'https://npm.ystel.cn/',
            // url: 'http://192.168.168.1:81/',
            desc: ''
        },
        {
            name: 'ssh',
            icon: 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=ssh',
            url: 'https://ssh.ystel.cn/',
            desc: ''
        },

    ]
}

const getUserDefult = () => {
    // changeNum: 0, // 该字段用来触发改变
    return {
        baseInfo: {
            userCode: '-1',
            userName: '访客',
        },
        extInfo: {
            common: {
                cardTransparency: '2',
            },
            bg: {
                // pc端背景
                pc: {
                    showType: 'url', // none:无背景 url:链接 color:颜色
                    urls: getBgImgUrlPcDefault(),
                    color: 'white',
                    autoChangeBg: { // 自动更新背景
                        isOpen: false,
                        interval: 30 // 单位秒
                    }
                },
                // 手机端背景
                mobile: {
                    showType: 'url', // none:无背景 url:链接 color:颜色
                    urls: getBgImgUrlMobileDefault(),
                    color: 'white',
                    autoChangeBg: { // 自动更新背景
                        isOpen: false,
                        interval: 30 // 单位秒
                    }
                }
            },
            // guides: getGuidesDefault(),
            guide: {
                showTitle: true,
                openUrlType: '_blank',
                // urls: getGuidesDefault(),
                urls: []
            },
            logo: {
                showType: 'none',
                url: ''
            },
            search: {
                sugSwitch: true,
                hisSwitch: true,
                engines: getSearchEnginesDefault(),
            }
        }
    }
};

// const user = useStorage('user', userDefult, undefined, {
//     serializer: StorageSerializers.object
// });

// const token = useStorage('token', '', undefined, {
//     serializer: StorageSerializers.string
// });

// onBeforeMount(() => {

// })

const user = useLocalStorage('user', getUserDefult());
const token = useLocalStorage('token', '');
const showBg = ref(false);


export const useUser = () => {

    const loginModel = ref({
        "username": '',
        "password": '',
        "password2": '',
        "email": '',
        "verifyCode": '',
    });

    const login = () => {

        const username = loginModel.value.username
        const password = loginModel.value.password

        if (isEmpty(username) || isEmpty(password)) {
            errorToast('登陆账号和密码不能为空')
            return
        }

        const loginApiData = {
            "appCode": "F0FB4BED6B664CFEBBB30A688A4C8E3F",
            "param": {
                "userName": username,
                "password": password
            }
        }

        loginApi(loginApiData).then(res => {
            if (res.code != '0') {
                errorToast('登录失败:' + res.message)
                return
            }
            successToast('登录成功')
            token.value = res.data;

            // 更新用户的 baseInfo
            // getUserInfo
            getUserInfoApi().then(getUserInfoRes => {
                let userBaseInfo = getUserInfoRes.data;
                user.value.baseInfo = {
                    userCode: userBaseInfo.userCode,
                    userName: userBaseInfo.userName,
                    createDate: userBaseInfo.createDate,
                    email: userBaseInfo.email,
                    appCode: userBaseInfo.appCode
                }
            })

            // 获取云端保存的ext数据
            getUserExtInfoApi().then(getUserExtInfoRes => {
                if (getUserExtInfoRes.code != '0') {
                    errorToast(getUserExtInfoRes.message)
                    return;
                }

                if (getUserExtInfoRes.data == undefined || getUserExtInfoRes.data == '') {
                    // 如果云端没有数据，就直接把本地保存好的数据写入云端
                    let setUserExtInfoData = {
                        appCode: 'F0FB4BED6B664CFEBBB30A688A4C8E3F',
                        param: {
                            userSet: user.value.extInfo
                        }
                    };
                    setUserExtInfoApi(setUserExtInfoData).then(setUserExtInfoDataRes => {
                        if (setUserExtInfoDataRes.code != '0') {
                            errorToast(setUserExtInfoDataRes.message)
                            return;
                        }
                    })
                } else {
                    // 云端有数据，就直接用云端数据覆盖本地数据
                    let userDate = getUserExtInfoRes.data;
                    user.value.extInfo = userDate.userSet;
                }
            })
        })

    };

    const loggedIn = computed(() => isNotEmpty(token.value))

    const logout = () => {
        // user.value = userDefult;
        token.value = '';
    }


    const regist = () => {

        const username = loginModel.value.username
        if (isEmpty(username)) {
            errorToast('登陆账号不能为空')
            return
        }

        const password = loginModel.value.password
        const password2 = loginModel.value.password2
        if (isEmpty(password) || isEmpty(password2)) {
            errorToast('密码不能为空')
            return
        }

        const email = loginModel.value.email
        if (isEmpty(email)) {
            errorToast('邮箱不能为空')
            return
        }
        const verifyCode = loginModel.value.verifyCode
        if (isEmpty(verifyCode)) {
            errorToast('验证码不能为空')
            return
        }
        // 校验2次输入的密码是否一致
        if (loginModel.value.password != loginModel.value.password2) {
            errorToast('密码不一致，请重新输入')
            return;
        }

        let data = {
            "appCode": "F0FB4BED6B664CFEBBB30A688A4C8E3F",
            "param": {
                "userName": username,
                "passWord": password,
                "email": email,
                "verifyCode": verifyCode,
            }
        }
        registApi(data).then(registApiRes => {
            if (registApiRes.code != '0') {
                errorToast('注册失败:' + registApiRes.message)
                return;
            }
            successToast('注册成功')
            // 返回到登录页面
            window.location.reload();
        }).catch(error => {
            errorToast(error)
        })
    };


    const sendRegistVerifyCode = () => {
        const email = loginModel.value.email
        if (isEmpty(email)) {
            errorToast('请先填写邮箱')
            return
        }

        let data = {
            "appCode": "F0FB4BED6B664CFEBBB30A688A4C8E3F",
            "param": {
                "email": email
            }
        }
        sendRegistVerifyCodeApi(data).then(sendRegistVerifyCodeApiRes => {
            if (sendRegistVerifyCodeApiRes.code == '0') {
                successToast('发送成功')
            } else {
                errorToast('发送失败:' + sendRegistVerifyCodeApiRes.message);
            }
        }).catch(error => {
            errorToast(error);
        })
    };

    const sendModifyPwdVerifyCode = () => {
        const email = loginModel.value.email
        if (isEmpty(email)) {
            errorToast('请先填写邮箱')
            return
        }

        let data = {
            "appCode": "F0FB4BED6B664CFEBBB30A688A4C8E3F",
            "param": {
                "email": email
            }
        }
        sendModifyPwdVerifyCodeApi(data).then(sendModifyPwdVerifyCodeApiRes => {
            if (sendModifyPwdVerifyCodeApiRes.code == '0') {
                successToast('发送成功')
            } else {
                errorToast('发送失败:' + sendModifyPwdVerifyCodeApiRes.message);
            }
        }).catch(error => {
            errorToast(error);
        })
    };

    // 防止计时器被覆盖
    const bgTimes = [];
    const setBg = (needUuid) => {
        // 只要定时器存在就直接清理掉
        bgTimes.forEach((item) => {
            clearTimeout(item)
        })

        let bgbox = document.querySelector('.bgbox')
        if (!bgbox) {
            return
        }

        // showBg.value = false;

        // bgbox.style.display = 'none' // 先隐藏

        let userInfo = user.value;

        let deviceType = getDeviceType();

        let bgInfo = userInfo?.extInfo?.bg[deviceType];

        let showType = bgInfo?.showType;
        if (showType == 'url') {
            const showUrl = getUserBgImgUrl(needUuid)
            // 如果是随机图片，loadImg 会多缓存了一次
            // loadImg(showUrl).then(() => {
            //     bgbox.style.backgroundImage = 'url(' + showUrl + ')'
            //     bgbox.style.backgroundColor = ''
            //
            //     // 为了触发动画
            //     showBg.value = false;
            //     nextTick(() => {
            //         showBg.value = true
            //     })
            // })

            bgbox.style.backgroundImage = 'url(' + showUrl + ')'
            bgbox.style.backgroundColor = ''

            // 为了触发动画
            showBg.value = false;
            nextTick(() => {
                showBg.value = true
            })

            const autoChangeBg = bgInfo.autoChangeBg || {};
            // 开关打开并且时间设置了时间间隔
            if (autoChangeBg.isOpen && autoChangeBg.interval) {
                // 提前缓存好下一次图片
                // const nextImgUrl = getUserBgImgUrl()
                // loadImg(nextImgUrl).then(() => {

                // })

                // 开启定时下一次执行时间
                const bgTime = setTimeout(() => {
                    setBg(true)
                }, autoChangeBg.interval * 1000);
                bgTimes.push(bgTime)

            }
        } else if (showType == 'color') {
            bgbox.style.backgroundImage = ''
            bgbox.style.backgroundColor = bgInfo.color
            showBg.value = false;
            nextTick(() => {
                showBg.value = true
            })
        } else {
            bgbox.style.backgroundImage = ''
            bgbox.style.backgroundColor = ''
            showBg.value = false;
            nextTick(() => {
                showBg.value = true
            })
        }
    }

    const getUserBgImgUrl = (needUuid) => {
        let userInfo = user.value;

        let deviceType = getDeviceType();

        let bgInfo = userInfo?.extInfo?.bg[deviceType];

        const urls = bgInfo.urls || [];
        const urlsChecked = urls.filter(item => item.checked);

        let showUrl;

        if (urlsChecked && urlsChecked.length > 0) {
            let size = urlsChecked.length;
            let index = parseInt(Math.random() * size); // 生成 [0,size-1] 的随机整数
            showUrl = urlsChecked[index].url;
        }

        if (needUuid != undefined && needUuid) {
            showUrl = getImgUrlUUID(showUrl)
        }

        return showUrl
    }

    const getImgUrlUUID = (imgUrl) => {
        if (imgUrl) {
            if (imgUrl.indexOf('?') > -1) {
                imgUrl += '&uuid=' + generateUUID()
            } else {
                imgUrl += '?uuid=' + generateUUID()
            }
        }
        return imgUrl;
    }


    const loadImg = async (imgUrl) => {
        return new Promise((resolve) => {
            let img = new Image();
            img.src = imgUrl;
            img.onload = () => {
                resolve()
            }
        })
    }

    const setBgInterval = () => {
        // if (bgInterval) {
        //     clearInterval(bgInterval)
        // }

        const autoChangeBg = bgInfo.autoChangeBg || {};
        if (autoChangeBg.isOpen && autoChangeBg.interval) {
            bgInterval = setInterval(() => {
                setBg()
            }, autoChangeBg.interval * 1000);
        }

        // const deviceType = getDeviceType();
        // const bgInfo = user.value.extInfo.bg[deviceType]

        // let showType = bgInfo?.showType;
        // if (showType == 'url') {
        //     const autoChangeBg = bgInfo.autoChangeBg || {};
        //     if (autoChangeBg.isOpen && autoChangeBg.interval) {
        //         bgInterval = setInterval(() => {
        //             setBg()
        //         }, autoChangeBg.interval * 1000);
        //     }
        // }

    }

    const resetUserInfo = () => {
        showConfirm({ content: '确认重置用户信息吗？' }).then(() => {
            const userDefault = getUserDefult();
            user.value = userDefault;
            saveUser2Db()
            setTimeout(() => {
                successToast('即将登出...')
                logout()
            }, 1000);

        }).catch(() => { })

    }

    const modifyUserPwd = () => {
        // const username = loginModel.value.username
        // if (isEmpty(username)) {
        //     errorToast('登陆账号不能为空')
        //     return
        // }

        const password = loginModel.value.password
        const password2 = loginModel.value.password2
        if (isEmpty(password) || isEmpty(password2)) {
            errorToast('密码不能为空')
            return
        }

        const email = loginModel.value.email
        if (isEmpty(email)) {
            errorToast('邮箱不能为空')
            return
        }
        const verifyCode = loginModel.value.verifyCode
        if (isEmpty(verifyCode)) {
            errorToast('验证码不能为空')
            return
        }
        // 校验2次输入的密码是否一致
        if (loginModel.value.password != loginModel.value.password2) {
            errorToast('密码不一致，请重新输入')
            return;
        }

        let data = {
            "appCode": "F0FB4BED6B664CFEBBB30A688A4C8E3F",
            "param": {
                "passWord": password,
                "email": email,
                "verifyCode": verifyCode,
            }
        }
        modifyUserPwdApi(data).then(modifyUserPwdApiRes => {
            if (modifyUserPwdApiRes.code != '0') {
                errorToast('修改失败:' + modifyUserPwdApiRes.message)
                return;
            }
            successToast('修改成功')
            // 返回到登录页面
            window.location.reload();
        }).catch(error => {
            errorToast(error)
        })
    }

    // onUnmounted(() => {
    //     if (bgInterval) {
    //         debugger
    //         clearInterval(bgInterval)
    //     }
    // })

    return {
        showBg,
        setBg,
        token,
        loginModel,
        user,
        login,
        loggedIn,
        logout,
        regist,
        sendRegistVerifyCode,
        getBgImgUrlPcDefault,
        getBgImgUrlMobileDefault,
        getSearchEnginesDefault,
        resetUserInfo,
        sendModifyPwdVerifyCode,
        modifyUserPwd
    }

}



